package com.marveal.rabbit.producer.config.database;

import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * 	$BrokerMessageConfiguration
 * 	进行数据库表结构的创建
 * @author Alienware
 *
 */
@Configuration
public class BrokerMessageConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(BrokerMessageConfiguration.class);

    @Resource(name = "rabbitProducerDataSource")
    private DataSource rabbitProducerDataSource;

    public BrokerMessageConfiguration() {
    }

    @Value("classpath:rabbit-producer-message-schema.sql")
    private org.springframework.core.io.Resource schemaScript;
    
    @Bean
    public DataSourceInitializer initDataSourceInitializer() {
        LOGGER.info("--------------rabbitProducerDataSource-----------: {}", JSONUtil.toJsonStr(rabbitProducerDataSource));
        final DataSourceInitializer initializer = new DataSourceInitializer();
        initializer.setDataSource(rabbitProducerDataSource);
        initializer.setDatabasePopulator(databasePopulator());
        return initializer;
    }

    private DatabasePopulator databasePopulator() {
        final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScript(schemaScript);
        return populator;
    }
}
